package com.ruoyi.web.controller.erp;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.erp.common.enums.OrderStatus;
import com.ruoyi.erp.domain.XzgOrder;
import com.ruoyi.erp.domain.dto.XzgOrderExcelDto;
import com.ruoyi.erp.domain.vo.XzgOrderVo;
import com.ruoyi.erp.service.IXzgOrderService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author qiuwencong
 * @Date 2021/12/6 10:35
 * @Package com.ruoyi.web.controller.erp
 * @Description
 */
@RestController
@RequestMapping("/erp/order")
public class OrderController extends BaseController {

    @Autowired
    private IXzgOrderService orderService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody XzgOrder order) {
        order.setCreateBy(getUsername());
        order.setUpdateBy(getUsername());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderStatus.NEW.getKey());
        if (Objects.isNull(order.getUserId())) {
            order.setUserId(getUserId());
        }
        return toAjax(orderService.insertOrder(order));
    }

    /**
     * 获取order列表
     *
     * @param order
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(XzgOrderVo order) {
        startPage();
        List<XzgOrderVo> orderList = orderService.selectOrderList(order);
        return getDataTable(orderList);
    }

    /**
     * 根据id获取order
     *
     * @param orderId
     * @return
     */
    @GetMapping("/{orderId}")
    public AjaxResult getById(@PathVariable Long orderId) {
        return AjaxResult.success(orderService.selectOrderById(orderId));
    }

    /**
     * 更新订单信息
     *
     * @param order
     * @return
     */
    @PutMapping
    public AjaxResult update(@Validated @RequestBody XzgOrder order) {
        order.setUpdateBy(getUsername());
        order.setUpdateTime(new Date());
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 检查是否有相同的订单合同号
     *
     * @param orderId
     * @param orderCode
     * @return
     */
    @GetMapping("/checkCode")
    public AjaxResult checkSameCode(Integer orderId, String orderCode) {
        return AjaxResult.success(orderService.selectSameCode(orderId, orderCode));
    }

    /**
     * 根据订单id修改订单状态
     *
     * @param orderId
     * @param status
     * @return
     */
    @PutMapping("/changeStatus/{orderId}/{status}")
    public AjaxResult changeStatus(@PathVariable Long orderId, @PathVariable String status) {
        XzgOrder order = new XzgOrder();
        order.setOrderId(orderId);
        order.setStatus(status);
        order.setUpdateBy(getUsername());
        order.setUpdateTime(new Date());
        return toAjax(orderService.changeOrderStatus(order, status));
    }

    /**
     * 根据id逻辑删除订单信息
     *
     * @param orderIds
     * @return
     */
    @DeleteMapping("/{orderIds}")
    public AjaxResult delete(@PathVariable Long[] orderIds) {
        return toAjax(orderService.deleteOrderById(orderIds, getUsername()));
    }

    /**
     * 下载模板
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<XzgOrderExcelDto> util = new ExcelUtil<>(XzgOrderExcelDto.class);
        String[] strings = Arrays.stream(OrderStatus.values()).map(OrderStatus::getValue).toArray(String[]::new);
        util.setDropDownSelection(strings);
        util.setSelectRange(new int[]{1, 200, 6, 6});
        util.importTemplateExcel(response, "订单数据");
    }

    /**
     * 导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<XzgOrderExcelDto> util = new ExcelUtil<>(XzgOrderExcelDto.class);
        List<XzgOrderExcelDto> orders = util.importExcel(file.getInputStream());
        Map<String, Long> userId = sysUserService.getUserId(orders.stream().map(XzgOrderExcelDto::getNickName).collect(Collectors.toList()));
        for (XzgOrderExcelDto order : orders) {
            if (userId.containsKey(order.getNickName())) {
                order.setUserId(userId.get(order.getNickName()));
            }
        }
        return AjaxResult.success(orderService.importOrders(orders, updateSupport, getUsername()));
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, XzgOrderVo order) {
        List<XzgOrderVo> orderList = orderService.selectOrderList(order);
        for (XzgOrderVo xzgOrderVo : orderList) {
            xzgOrderVo.setStatus(OrderStatus.getValueByKey(xzgOrderVo.getStatus()));
        }
        ExcelUtil<XzgOrderVo> util = new ExcelUtil<>(XzgOrderVo.class);
        util.exportExcel(response, orderList, "订单数据");
    }

}
